
package roomeditor;

import java.applet.Applet;
import java.awt.Graphics;
import gamepack.Game;
import gamepack.*; //comment later

import java.io.*;
import java.util.*;
import javax.swing.*;        
import java.awt.*;
import java.awt.event.*;  // mouse events
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.border.*;
import gamepack.*;

/*------------------
Agenda - 
[done]  Proper Transparent blits along with Background Image.
[done]  Save and Load .room file with w,h, filename, 
                                   vx,vy,vw,vh, vl, vu, vr, vd.

[done] Addon Change Grid Size | View Mouse Co-ordinates

Enable tankattack to load .room file
*/


public class RoomEditor extends Applet {


	public static MyPanel spnl;	
	public static String saveFile; 
	
/**
 * RuntimeException requires this. (Prevents Warning during compilation)
 */
static final long serialVersionUID = 42L;
                                                                     // For non animation applications, the painter is set to null.
	public void init() 	{	 Game.init(800,600,new RoomEditor(), null ,null, null);  /*new TankAttackWorld(); */ 
									 		         // applet, frame, layout, painter
	}

	//public void update(Graphics g) {}
	public void paint(Graphics g) {	
		super.paint(g);
		// If this was a backbuffer animation game then you only need to call Game.paint(g); 
						  // else if this is an widget application, then write your code to paint here on widgets
	}
	
	public static JComboBox createChoiceBox(String[] str) {
		JComboBox choicebox = new JComboBox();
		for( int i=0;i<str.length;i++) {
			choicebox.addItem(str[i]);
		}
		return choicebox;
	}
	public static void modifyChoiceBox(JComboBox c,String[] str) {
		c.removeAllItems();
		for( int i=0;i<str.length;i++) {
			c.addItem(str[i]);
		}
	}
	
	public static JComboBox c1;
	public static JComboBox c2;
	public static Map<String, PreferredSpawnString> mapStrPSS;
	
	public static String[] getPSSNames(Resource res) {
		mapStrPSS = new HashMap<String,PreferredSpawnString>();
		int len = res.pss.length;
		String[] str_arr = new String[len];
		for(int i=0;i<len;i++) {
			str_arr[i] = res.pss[i].name;
			mapStrPSS.put( res.pss[i].name , res.pss[i] );
		}
		return str_arr;
	}
		
	public static String[] readSpriteNamesFromFile() {
		Vector<String> vecStr = new Vector<String>();
		String curLine;
		try {
			BufferedReader in = new BufferedReader(new FileReader( RoomEditor.spriteLib ));
			while (( curLine = in.readLine()) != null) {
				System.out.println( curLine);
				vecStr.add(curLine);
			} 
		
			in.close();
		} catch (FileNotFoundException e) {   e.printStackTrace();		} 
		catch ( IOException ioe ) {   System.out.println( ioe.getMessage() ); 	}
		
		return vecStr.toArray( new String[0] ); 
	}
	public static boolean autoLoadOnStartUp = false;
	public static Resource res;
	public static boolean showBackground = true;
	public static boolean showOutline = false;
	public static boolean showViewport = false;
	
	public static boolean startWithSpriteOutlines = false;
	public static boolean startWithShowGrid = false;
	public static boolean startWithSnapToGrid = true;
	public static boolean startWithShowBackground = true;
	public static boolean startWithShowViewport = false;
	
	
	public static String spriteLib;
	
	public static int roomWidth = 1300;
	public static int roomHeight = 1100;
	public static int vx,vy,vw,vh,vl,vr,vu,vd;
	public static String line1 = "100 , 100 , default.gif ";
	public static String line2 = "0,0,100,100, 10,10,10,10 ";
	public static int gw = 50; // some dummy initial value, actual value is read from config file.
	public static int gh = 50;
	
	public static Cursor nCursor = new Cursor(Cursor.DEFAULT_CURSOR);
	public static Cursor moCursor = new Cursor(Cursor.HAND_CURSOR);

	public static void initVars() {
		System.out.println("initVars()");
		Resource r = ResourceLoader.getResource("roomeditor.App");		
		
		autoLoadOnStartUp = ( r.getValueAsInt("autoLoadOnStartUp") == 0 ) ? false : true ; 
		gw = r.getValueAsInt("gw");
		gh = r.getValueAsInt("gh");
		saveFile = r.getValue("saveFile");
		roomWidth = r.getValueAsInt("roomWidth");
		roomHeight = r.getValueAsInt("roomHeight");
		bkImageFile = r.getValue("bkImageFile");
		spriteLib = r.getValue("spriteLib");

	startWithSpriteOutlines = r.getValueAsInt("startWithSpriteOutlines") == 0 ? false : true;
	startWithShowGrid = r.getValueAsInt("startWithShowGrid") == 0 ? false : true;
	startWithSnapToGrid = r.getValueAsInt("startWithSnapToGrid") == 0 ? false : true;
	startWithShowBackground = r.getValueAsInt("startWithShowBackground") == 0 ? false : true;
	startWithShowViewport = r.getValueAsInt("startWithShowViewport") == 0 ? false : true;		
	
	showViewport = startWithShowViewport;
	showBackground = startWithShowBackground;
	showOutline = startWithSpriteOutlines;
	showViewport = startWithShowViewport;
	MyPanel.showGrid = startWithShowGrid;
	
		vx = r.getValueAsInt("vx");
		vy = r.getValueAsInt("vy");
		vw = r.getValueAsInt("vw");
		vh = r.getValueAsInt("vh");
		
		vl = r.getValueAsInt("vl");
		vr = r.getValueAsInt("vr");
		vu = r.getValueAsInt("vu");
		vd = r.getValueAsInt("vd");	

		appWindowWidth = r.getValueAsInt("appWindowWidth");
		appWindowHeight = r.getValueAsInt("appWindowHeight");
	}


	public static String bkImageFile = "";
	public static CImage bkcimg;
	public static PreferredSpawnString bkpss;
	public static SpriteIcon bkSpriteIcon;
	
	public static int appWindowWidth;
	public static int appWindowHeight;
	public static void setBackgroundImage(String str) {
		 RoomEditor.bkImageFile = str;
		 Image bkimg = ResourceLoader.getImage( RoomEditor.bkImageFile );		 
		 RoomEditor.bkcimg = new CImage(bkimg);  //RoomEditor.res.img[0][0];				 
		 RoomEditor.bkpss = new PreferredSpawnString("spawnStr",bkcimg,"name","0,0",0) ;
		 if( bkSpriteIcon != null ) {
			bkSpriteIcon.pss = bkpss;
		}		 
	}
	
	public static JLabel label = new JLabel();
	public static Frame frame;
	public static void main(String args[]) {
	
			frame = new Frame("Room Editor");
			Game.init(800,600,new RoomEditor(),frame, new BorderLayout(),null );
			ResourceLoader.rootDir = "";			
			initVars();

			//Application.f.remove( Application.a );			
			//Application.f.setLayout( new BorderLayout() );
			//Application.f.add( Application.a );
			
			Application.f.setExtendedState( Frame.MAXIMIZED_BOTH );
			
			//Rectangle rt = frame.getMaximizedBounds();			
			//System.out.println( "maxBounds = " + rt);
			//System.out.println(" maxSize = " + frame.getMaximumSize() );
			//frame.setExtendedState( Frame.MAXIMIZED_BOTH );
			
			//Application.resize( appWindowWidth, appWindowHeight);
			res = ResourceLoader.getResource("roomeditor.App");			
			System.out.println(" roomResource = " + res );
			
		
		Box box = Box.createHorizontalBox();
		Box vbox = Box.createVerticalBox();
		Border border = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); //BorderFactory.createLineBorder(Color.black)
		box.setBorder( border); 
		vbox.setBorder( border );
		 String[] str_arr1 = readSpriteNamesFromFile();
		 Application.c.setLayout( new BorderLayout() );
		 
		 c1 = createChoiceBox( str_arr1 );
		 c1.addItemListener( new SpriteItemListener() );
		 //Application.c.add(c1);
		box.add(c1);

		 String[] str_arr2 = { "select a sprite first" };
		 c2 = createChoiceBox( str_arr2 );
		 c2.addItemListener( new PSSItemListener() );
		 //Application.c.add(c2 );
		box.add(c2);
		
		JButton saveButton = new JButton("Save");
		JButton loadButton = new JButton("Load");
		JToggleButton gridButton = new JToggleButton("Display Grid", startWithShowGrid);
		JToggleButton stickyButton = new JToggleButton("Snap To Grid",startWithSnapToGrid);
		JToggleButton backgroundButton = new JToggleButton("Display Background",startWithShowBackground);
		JToggleButton imageOutlineButton = new JToggleButton("Dislay Image Outline", startWithSpriteOutlines);
		JToggleButton showViewportButton = new JToggleButton("Dislay ViewPort", startWithShowViewport);
		
		saveButton.addActionListener( new SaveRoomFile() );
		loadButton.addActionListener( new LoadRoomFile() );
		stickyButton.addActionListener( new ActionListener() { 
				public void actionPerformed(ActionEvent e)  {
					MyPanel.sticky = MyPanel.sticky ? false : true; 
				} 
														   } );
		gridButton.addActionListener( new ActionListener() { 
				public void actionPerformed(ActionEvent e)  {
					MyPanel.showGrid = MyPanel.showGrid ? false : true; 
					MyPanel.singleton.repaint();
				} 
														   } );														   
		backgroundButton.addActionListener( new ActionListener() { 
				public void actionPerformed(ActionEvent e)  {
					RoomEditor.showBackground = RoomEditor.showBackground ? false : true;
					MyPanel.singleton.repaint();
				} 
														   } );														   
		imageOutlineButton.addActionListener( new ActionListener() { 
				public void actionPerformed(ActionEvent e)  {
					RoomEditor.showOutline = RoomEditor.showOutline ? false : true;
					MyPanel.singleton.repaint();
				} 
														   } );														   
		showViewportButton.addActionListener( new ActionListener() { 
				public void actionPerformed(ActionEvent e)  {
					RoomEditor.showViewport = RoomEditor.showViewport ? false : true;
					MyPanel.singleton.repaint();
				} 
														   } );
		
														   
				
		
		PreferredSpawnString dummypss = new PreferredSpawnString("String",null,"String","String",0);
 		 PreviewWindow pw = new PreviewWindow(100,100,dummypss); // "Preview Window", "No spawn String", "No index String"); 
		 //Application.c.add( pw );
		vbox.add( pw );

		/*Application.c.add(saveButton);
		Application.c.add(loadButton);
		Application.c.add(gridButton);
		Application.c.add(stickyButton);
		Application.c.add(backgroundButton);
		Application.c.add(imageOutlineButton); */

		box.add(saveButton);
		box.add(loadButton);
		
		vbox.add(gridButton);
		vbox.add(stickyButton);
		vbox.add(backgroundButton);
		vbox.add(imageOutlineButton);
		vbox.add(showViewportButton);
		
		vbox.add( Box.createVerticalGlue() );
		vbox.add( Box.createVerticalGlue() );
		
		 //c1.select(0);
		 c1.setSelectedIndex(0);
		 Resource res = ResourceLoader.getResource( (String) c1.getItemAt(0) );		 
		 String[] str_arr3 = getPSSNames(res);		 		 
		 modifyChoiceBox( c2, str_arr3 );
		 //c2.select(0);
		 c2.setSelectedIndex(0);
		PreviewWindow.pstr 				  = RoomEditor.mapStrPSS.get       ( RoomEditor.c2.getItemAt(0) );
		PreviewWindow.singleton.repaint();

		//ImageIcon ico = new ImageIcon( PreviewWindow.pstr.cimg.img );
		//label.setIcon( ico );
		label.setText( "Mouse Co-ordinates");
		Application.c.add( label , BorderLayout.SOUTH);
		
		 // ---------------------------------------------
		 
		 
		 spnl = new MyPanel( RoomEditor.roomWidth ,RoomEditor.roomHeight );		 
		 spnl.setPreferredSize( new Dimension( RoomEditor.roomWidth, RoomEditor.roomHeight ) );
		 spnl.setLayout(null);
		 
		 JScrollPane sp = new JScrollPane( spnl );
		 sp.setPreferredSize( new Dimension(900,600) );
		 sp.setMaximumSize( new Dimension( RoomEditor.roomWidth, RoomEditor.roomHeight ) );
		 Application.c.add(sp);
		 Application.c.add( box, BorderLayout.NORTH ); 
		 Application.c.add( vbox, BorderLayout.WEST );
		 spnl.revalidate();
		 //Application.c.add( new Button("This is a very long button..................") );
		 
		 setBackgroundImage( RoomEditor.bkImageFile );
		 SpriteIcon.bkgndCreationFlag = true;		 
		 new SpriteIcon( 0,0, bkpss ); // sets bkgndCreationFlag to false
		
		if ( autoLoadOnStartUp ) {
			SpriteIcon.loadSpriteDetails();
		}
		frame.setVisible(true);
	}
}

class SaveRoomFile implements ActionListener {
	public void actionPerformed(ActionEvent e)  {
		System.out.println("Save room file invoked");
		SpriteIcon.dumpSpriteDetails();
	} 
}

class LoadRoomFile implements ActionListener {
	public void actionPerformed(ActionEvent e)  {
		System.out.println("Load room file invoked");
		SpriteIcon.loadSpriteDetails();
		MyPanel.singleton.repaint();
	} 
}

class PSSItemListener implements ItemListener {

	public void itemStateChanged(ItemEvent e) {
		if ( e.getID() == e.ITEM_STATE_CHANGED ) {
			//System.out.println("PSSItemListener Invoked!!!" + e.getItem() );
			PreviewWindow.pstr = RoomEditor.mapStrPSS.get( e.getItem() );		
			if ( PreviewWindow.pstr != null && PreviewWindow.pstr.cimg != null ) {
				//RoomEditor.label.setIcon( new ImageIcon( PreviewWindow.pstr.cimg.img ) );
			}
			PreviewWindow.singleton.repaint();
		}
	}
 
}

class SpriteItemListener implements ItemListener {

	public void itemStateChanged(ItemEvent e) {
		if ( e.getID() == e.ITEM_STATE_CHANGED ) {
			//System.out.println("SpriteItemListener Invoked!!!" + e.getItem() );
			String spriteName = (String) e.getItem();
			Resource res = ResourceLoader.getResource( spriteName );
			String[] str_arr3 = RoomEditor.getPSSNames(res);		 		 
			RoomEditor.modifyChoiceBox( RoomEditor.c2, str_arr3 );
			RoomEditor.c2.setSelectedIndex(0);
			PreviewWindow.pstr = RoomEditor.mapStrPSS.get( RoomEditor.c2.getItemAt(0) );

			if ( PreviewWindow.pstr != null && PreviewWindow.pstr.cimg != null ) {
				//RoomEditor.label.setIcon( new ImageIcon( PreviewWindow.pstr.cimg.img ) );
			}
			//RoomEditor.label.setIcon( new ImageIcon( PreviewWindow.pstr.cimg.img ) );
			PreviewWindow.singleton.repaint();
		}
	}
 
}

class PreviewWindow extends JPanel {

	//public static CImage preview_cimg; // pstr.cimg
	//public static String preview_spawnString; // pstr.spawnString
	//public static String preview_cimg_index;  // does not exist
	//public static String preview_indexString; // pstr.indexStr
	//String imgName;                          // pstr.name                         
	
	public static PreferredSpawnString pstr;
	
	public static PreviewWindow singleton;
	PreviewWindow(int width, int height, PreferredSpawnString prefss) { //,String name, String spwnStr, String indStr) {
		//setOpaque(false);
		//setSize(width,height);
		setPreferredSize( new Dimension(100,100) );
		setSize(100,100);
		pstr = prefss;
		singleton = this;
		
		//imgName = pstr.name;
		//preview_spawnString = pstr.spawnString; 
		//preview_indexString = pstr.indexStr; 
	}
	public void paint(Graphics g) {
		super.paint(g);		

		Dimension d = getSize();
		//System.out.println("**************************  Painting PreviewWindow - size - " + d );
		//Point p = getLocation();
		g.setColor(Color.black);
		g.drawRect( 0, 0, d.width-1, d.height-1 );    // Draw the bounding rect of preview window
		if( pstr != null && pstr.cimg != null  ) {
			int cx = d.width/2;
			int cy = d.height/2;
			if ( pstr.cimg.img != null ) {				
				g.drawImage(pstr.cimg.img, cx+ pstr.cimg.x, cy+ pstr.cimg.y ,null);
			}
		}
	}
}

class SpriteIcon extends JPanel implements MouseMotionListener, MouseListener {
	
	// The dimension and location of this canvas must be same as its cimg's bounding rect and cimg's center 
	String imgName;	 // Not useful dummy	 // pss.name
	CImage cimg;	// The CImage associated.  // pss.cimg
	String spawnString; // Associated spawnstring  // pss.spawnStr
	String indexString; // Associated indexString  // pss.indexString         
	PreferredSpawnString pss;
	
	int cx,cy;		// These basically point to cimg.x and cimg.y
	Rectangle cr;	// points to cimg.sr
		
	int x,y;  // The location where mouse is clicked, Passed through constructor where this SpriteIcon 
			  // will be placed. Used to setLocation(x+cx,y+cy); // r.x+cx and r.width
	
	static Vector<SpriteIcon> vec_spr_icon = new Vector<SpriteIcon>();
		
	private int ax,ay; // anchor for mouse; For internal mouse tracking purpose.
	
	static SpriteIcon bkgnd;
	static boolean bkgndCreationFlag = false;
	
	SpriteIcon(int xx, int yy,PreferredSpawnString pss_) { //String name,CImage cimage,String spawnStr,String iStr) {
		
		pss = pss_;
		String name = pss.name;
		CImage cimage = pss.cimg;
		String spawnStr = pss.spawnString;
		String iStr = pss.indexStr;
		
		x = xx;
		y = yy;
		spawnString = spawnStr;
		indexString = iStr;
		if( cimage == null ) {
			cx=0; 
			cy=0; 
			cr = new Rectangle(0,0,150,150);
		} else {
			cx = cimage.x;
			cy = cimage.y;
			cr = cimage.getBounds();
		}
		setOpaque(false);
		cimg = cimage;
		imgName = name;		
		setSize( cimg.img.getWidth(null), cimg.img.getHeight(null));
		
		if ( bkgndCreationFlag == false ) {
			addMouseMotionListener(this);
			addMouseListener(this);
			setLocation(x + cx ,y + cy);			
			vec_spr_icon.add(this);
			// first remove bkgnd and add it at the end, since the last SpriteIcon is drawn first. <Start Transparency Hack>
			if( bkgnd != null ) {
				RoomEditor.spnl.remove(bkgnd);
				RoomEditor.spnl.add(this);
				RoomEditor.spnl.add(bkgnd);			
			} else {
				RoomEditor.spnl.add(this);
			}
			// </ End Tansparency Hack>
		} else {
			bkgndCreationFlag = false;
			bkgnd = this;
			setLocation(0,0);
			RoomEditor.spnl.add(this); // no prob, since this is added last will be displayed first.
		}
	}
	
	public void setPosition(int posx,int posy) {
		x = posx;  y = posy;
		setLocation( x + cx, y + cy );
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		
		Dimension d = getSize();
		Point p = getLocation();
		g.setColor(Color.red);

		int pos = vec_spr_icon.indexOf(this) + 1;
		boolean firstSpriteIconPaint =  (pos == vec_spr_icon.size() ) ? true : false;		
		//System.out.println("***SPRITEICON.paint() pos = " + pos  + " maxsize = " + vec_spr_icon.size() + " is first = " + firstSpriteIconPaint );

		if( bkgnd == this ) {
			if ( RoomEditor.showBackground ) {
				//Resource res  = RoomEditor.res;			
				if ( RoomEditor.bkcimg != null ) {
				//if ( res != null && res.img != null) {
					Image img = RoomEditor.bkcimg.img;				
					if ( img != null ) {
						//System.out.println(" drawing bkgnd");
						g.drawImage( img, 0,0,null);
					}
				}		
			} 
			return;	
		}
		
		if( cimg != null && cimg.img != null ) {
			int w = cimg.img.getWidth(null);
			int h = cimg.img.getHeight(null);
			g.drawImage( cimg.img, 0, 0 ,null );
			cx = -cimg.x;
			cy = -cimg.y;
			if ( RoomEditor.showOutline ) {
				g.drawRect( (cx)-1 , (cy)-1, 2, 2);
			}
		} 
		if( RoomEditor.showOutline ) {	
			g.setColor(Color.red);
			if( !cimg.hasSubShape() ) {
				g.drawRect( 0, 0, d.width-1, d.height-1 );
			} else {
				Polygon pz = cimg.getSubShape();
				Polygon clone = new Polygon( pz.xpoints, pz.ypoints, pz.npoints );
				clone.translate( -cimg.x , -cimg.y );				
				g.drawPolygon( clone );
			}
		}
		// ----------------------------
		//int h = g.getFontMetrics().getHeight(); //stringWidth(imgName);
		//g.drawString(imgName,0,h);
		g.setColor(Color.black);			
	}		
	public static void dumpSpriteDetails() {
		try {
			FileWriter fw = new FileWriter( RoomEditor.saveFile );
			System.out.print( RoomEditor.line1 + "\n"); 			
			System.out.print( RoomEditor.line2 + "\n"); 
			fw.write( RoomEditor.line1 + "\n" );  // line1 is read from a file and doesn't contain \n 
			fw.write( RoomEditor.line2 + "\n" );
			for( int i=0; i< vec_spr_icon.size(); i++) {
				SpriteIcon si = vec_spr_icon.get(i);
				//String str = "SpriteIcon("+i+") = Location = " + si.x + "," + si.y + ", spawnstring = " + si.spawnString + "\n";				
				//String str = String.format( si.spawnString, si.x, si.y ); 	str = str + "\n"; 	str = si.pss.pos + " # " + str;
				String str = String.format("%d,%d,%d # %s \n", si.x,si.y, si.pss.pos, si.spawnString );
				System.out.print( str );
				fw.write( str );
			}
			fw.close();
		} catch ( java.io.IOException ioe ) {   System.out.println( ioe.getMessage() ); }
	}
	public static void loadSpriteDetails() {
		Vector<String> vecStr = new Vector<String>();
		String curLine;
		// Remove existing spriteIcons from panel.
		for( int i=0;i<vec_spr_icon.size();i++ ) {
			RoomEditor.spnl.remove( vec_spr_icon.get(i) );
		}		
		vec_spr_icon.clear();
		
		try {
			BufferedReader in = new BufferedReader(new FileReader( RoomEditor.saveFile ));
				if (( curLine = in.readLine()) == null) { throw new RuntimeException("Incorrect format of Room file. Line(1)"); }
				RoomEditor.line1 = curLine;
				System.out.println("Reading first line = " + curLine );
				if (( curLine = in.readLine()) == null) { throw new RuntimeException("Incorrect format of Room file Line(2)"); }
				RoomEditor.line2 = curLine;
			String[] parts = curLine.split(","); 
			if( parts.length < 8) { 
				throw new RuntimeException("Incorrect format of room file - Line #2 Check if all 8 view port parameters are present"); 
			}

			RoomEditor.vx = Integer.parseInt(parts[0].trim());
			RoomEditor.vy = Integer.parseInt(parts[1].trim());
			RoomEditor.vw = Integer.parseInt(parts[2].trim());
			RoomEditor.vh = Integer.parseInt(parts[3].trim());
			RoomEditor.vl = Integer.parseInt(parts[4].trim());
			RoomEditor.vr = Integer.parseInt(parts[5].trim());
			RoomEditor.vu = Integer.parseInt(parts[6].trim());
			RoomEditor.vd = Integer.parseInt(parts[7].trim());
				
				System.out.println("Reading second line = " + curLine );			
			
			while (( curLine = in.readLine()) != null) {
			
				System.out.println( curLine);
				int index = curLine.indexOf('#');
				String part1 = curLine.substring( 0 , index);
				String part2 = curLine.substring(index+1, curLine.length() );
				part1 = part1.trim();  part2 = part2.trim();
				int index2 = part2.indexOf('#');
				String spriteName = part2.substring( 0 , index2);
				spriteName = spriteName.trim();
				
				String[] partsOfLine1 = part1.split(",");
				if ( partsOfLine1.length < 3 ) { throw new RuntimeException(" Invalid data in room file"); }
				int spriteX = Integer.parseInt( partsOfLine1[0] );
				int spriteY = Integer.parseInt( partsOfLine1[1] );
				int spritePos = Integer.parseInt( partsOfLine1[2] );
				String sss = String.format("%d %d %d %s ", spriteX, spriteY,spritePos,spriteName );
				
				Resource res = ResourceLoader.getResource( spriteName );
				PreferredSpawnString p = res.pss[spritePos];
				new SpriteIcon( spriteX, spriteY, p );
					
				vecStr.add(curLine);
			} 		
			in.close();
		} catch (FileNotFoundException e) {   e.printStackTrace();		} 
		catch ( IOException ioe ) {   System.out.println( ioe.getMessage() ); 	}
	}
	
	
	public void mouseClicked(MouseEvent e) { // Invoked when the mouse button has been clicked (pressed and released) on a component. 
		if( e.getButton() == MouseEvent.BUTTON3 ) {
			System.out.println("Right click - Deleting SpriteIcon");
			vec_spr_icon.remove(this);
			RoomEditor.spnl.remove(this);
			RoomEditor.spnl.repaint();
		}
		if( e.getButton() == MouseEvent.BUTTON1 ) {			
			RoomEditor.frame.pack();
			System.out.println("Mouse clicked on a sprite --- Want to edit this sprite's properties? Not supported in this version.");
		}
	}
 public void mouseEntered(MouseEvent e) { //  Invoked when the mouse enters a component. 
 }
 public void mouseExited(MouseEvent e) { // Invoked when the mouse exits a component. 
 }
 public void mousePressed(MouseEvent e) { // Invoked when a mouse button has been pressed on a component. 
	Point p = e.getPoint();
	ax = p.x;  
	ay = p.y;
	//System.out.println(" Anchor point -->: " + p );	
 }
 public void mouseReleased(MouseEvent e) { // Invoked when a mouse button has been released on a component. 
 }

 public static Point correction( Point mp ) {
	float x = mp.x;
	float y = mp.y;
	float fx = x/RoomEditor.gw;
	float fy = y/RoomEditor.gh;
	int lx = Math.round(fx);
	int ly = Math.round(fy);
	Point endPoint = new Point( lx * RoomEditor.gw , ly * RoomEditor.gh );
	Point retPoint  = new Point( endPoint.x - mp.x, endPoint.y - mp.y );
	return retPoint; 
 }
 
public void mouseDragged(MouseEvent e) { // Invoked when a mouse button is pressed on a component and then dragged. 
	setCursor( RoomEditor.moCursor );
	Point p = e.getPoint();
	//System.out.println("dragged = " + e.getPoint() );
	int dx = p.x - ax;
	int dy = p.y - ay;
	Point loc = getLocation();
	loc.translate( dx ,dy );
	
	if ( MyPanel.sticky ) {
		Point cor = correction( loc );
		loc.translate( cor.x,cor.y );
		//System.out.println(" setLocation : " + loc + " correction = " + cor );
	}
	
	setLocation( loc );
	
	x = loc.x + cx;
	y = loc.y + cy;
	MyPanel.singleton.repaint();

}
 public void mouseMoved(MouseEvent e) { // Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. 
	setCursor( RoomEditor.moCursor );
 }
}

class MyPanel extends JPanel implements MouseListener , MouseMotionListener {

	public static int gx,gy;
	//public static int gw = 20;
	//public static int gh = 20;
	public static boolean showGrid = false;
	public static boolean sticky = true;
	public static MyPanel singleton;
	public static boolean showBackground = true;
	public static boolean opaque=true;
	
	public void paint(Graphics g) {	
		super.paint(g);
		if( showGrid ) {
			Dimension d = Application.getSize();
			//System.out.println("Width = " + RoomEditor.roomWidth + " Height = " + RoomEditor.roomHeight );
			for(int i=0;i< RoomEditor.roomWidth; i+= RoomEditor.gw ) {  // draw vertical lines
				g.drawLine( i, 0, i, RoomEditor.roomHeight );
			}
			for(int i=0;i<RoomEditor.roomHeight; i+= RoomEditor.gh ) {  // draw horizontal lines
				g.drawLine( 0, i, RoomEditor.roomWidth, i  );
			}
		}
		if( RoomEditor.showViewport ) {			
			int vx = RoomEditor.vx;			int vy = RoomEditor.vy;
			int vw = RoomEditor.vw;			int vh = RoomEditor.vh;
			int vl = RoomEditor.vl;			int vr = RoomEditor.vr;
			int vu = RoomEditor.vu;			int vd = RoomEditor.vd;
			g.drawRect (vx, vy, vw,vh);
			g.drawRect ( vx+vl, vy+vu, vw-vl-vr, vh-vu-vd );
		}
	}

MyPanel(int width, int height) {
	setSize(width,height);
	setLocation(0,0);
	addMouseListener(this);
	addMouseMotionListener(this);
	singleton = this;
	
	setOpaque( opaque ); // Making this transparent has caused problem with rendering while dragging around spriteicons. 
}

	public void mouseClicked(MouseEvent e) { // Invoked when the mouse button has been clicked (pressed and released) on a component. 
		//System.out.println("Mouse clicked inside PANEL!!!!!!!!!!!!!!!");
		Point p = e.getPoint();		
		SpriteIcon s1 = new SpriteIcon( p.x, p.y , PreviewWindow.pstr); 
		setCursor( RoomEditor.moCursor );
		System.out.println(" Mouse Clicked - Creating sprite at " + p );
		MyPanel.singleton.repaint();
	}
	public void mouseMoved(MouseEvent e)  {
		Point p = e.getPoint();
		RoomEditor.label.setText( ""+ p.x + "," + p.y );
		setCursor( RoomEditor.nCursor );
	}
	public void mouseDragged(MouseEvent e) {
		
		Point p = e.getPoint();
		RoomEditor.label.setText( ""+ p.x + "," + p.y );	
	} 
 
 public void mouseEntered(MouseEvent e) { //  Invoked when the mouse enters a component. 
 }
 public void mouseExited(MouseEvent e) { // Invoked when the mouse exits a component. 
 }
 public void mousePressed(MouseEvent e) { // Invoked when a mouse button has been pressed on a component. 
 }
 public void mouseReleased(MouseEvent e) { // Invoked when a mouse button has been released on a component. 
 }

}

/*
SpriteCombo box
curFrameCombo box
Preview Window - Panel
Scroll Pane
Select and Move | Edit Sprite Option.

*/
